<template>
  <view class="layout" scroll-y="true">
    <VersionHeader :version_control="isVersionControl"></VersionHeader>
    <view
      class=""
      style="
        justify-content: space-between;
        margin: 50rpx auto;
        margin-top: 20rpx;
      "
    >
      <view class="center">
        <text
          class="loss center"
          style="margin-bottom: 10rpx; margin-right: 20rpx"
          >速度损失</text
        >
        <!-- <view class="center">
					<VersionCanvas :father-msg="v_loss"></VersionCanvas>
					<view @click="toggleMute" style="width: 50rpx; height: 50rpx; margin-top: 120rpx; ">
						<img :src="isMuted ? img_url[1] : img_url[0]" style="height: 100%; width: 100%;" alt="" />
					</view>
				</view> -->
        <view class="" style="">
          <view class="slider-bar" style="">
            <view class="bar red_none" :style="{ width: red_none }"></view>
            <view class="bar red_cover" :style="{ width: red_cover }"></view>
            <view class="bar purple" style="width: 20%"></view>
            <view
              class="bar green_cover"
              :style="{ width: green_cover }"
            ></view>
            <view class="bar green_none" :style="{ width: green_none }"></view>

            <view
              class="circle"
              :style="{ right: circlePosition, border: circle }"
            ></view>
          </view>
          <view class="labels">
            <text style="margin-right: 200rpx">偏高</text>
            <text>合适</text>
            <text>偏低</text>
          </view>
        </view>
      </view>
    </view>
    <view class="center" style="width: 100%">
      <view class="tips_header" style="position: relative; display: flex">
        <view class="" style="margin-left: 18rpx"> 提示： </view>
        <view class="">
          {{ tips }}
        </view>
        <img
          src="http://182.92.108.71:9001/image/vbt页建议框右侧.png"
          alt=""
          style="
            width: 80rpx;
            height: 80rpx;
            position: absolute;
            right: -15rpx;
            bottom: -15rpx;
          "
        />
      </view>
    </view>
    <view
      class="center"
      style="
        justify-content: space-between;
        height: 64rpx;
        margin: 10rpx 170rpx;
        margin-top: 60rpx;
      "
    >
      <view class="gi_module center">
        第
        <view class="s_n">{{ group }}</view>
        组
      </view>
      <view class="gi_module center">
        第
        <view class="s_n">{{ index }}</view>
        个
      </view>
    </view>
    <view class="index_box" style="width: 100%">
      <view class="center" style="flex-wrap: wrap">
        <view
          v-for="(index, indexKey) in arrs"
          :key="indexKey"
          class="index_module"
        >
          <view class="index_name center" style="margin-top: 5rpx">{{
            index.name
          }}</view>
          <view class="center" style="margin-top: 5rpx">
            <view
              class="index_value center"
              style="margin-left: 10rpx; justify-content: left"
            >
              {{ index.value }}
            </view>
            <view class="index_unit">
              {{ index.unit }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="br center" style="justify-content: left; margin-top: 70rpx">
      <view class="br_name"> 1RM </view>
      <view class="" style="">
        <input
          style=""
          v-model="rm"
          @blur="check_burden_value"
          class="br_value"
          type="text"
          placeholder="点击输入 >"
        />
      </view>
    </view>
    <view class="br center" style="justify-content: left; margin-bottom: 20rpx">
      <view class="br_name"> 负荷 </view>
      <view class="" style="">
        <input
          style=""
          v-model="burden"
          @blur="check_bd_value"
          class="br_value"
          type="text"
          placeholder="建议负荷 >"
        />
      </view>
    </view>

    <view class="" style="width: 100%; position: absolute; bottom: 40rpx">
      <view
        class=""
        style="
          display: flex;
          align-items: center;
          padding: 0px 45rpx;
          justify-content: space-between;
        "
      >
        <view
          @click="gotoDefine"
          class="bottom_button center"
          style="width: 140rpx"
        >
          指标释义
        </view>
        <view class="center">
          <view
            @click="goOneRm"
            class="bottom_button center"
            style="width: 140rpx"
          >
            测1RM
          </view>
          <view
            @click="tips_1rm"
            class="center"
            style="
              margin-bottom: 30rpx;
              margin-left: -15rpx;
              height: 40rpx;
              width: 40rpx;
              color: white;
              border-radius: 50%;
              background: rgba(110, 88, 170, 1);
            "
          >
            ?</view
          >
        </view>
        <view
          v-if="!isStart"
          @click="start"
          class="bottom_button center"
          style="width: 160rpx"
        >
          <img
            style="width: 30rpx; height: 30rpx; margin-right: 10rpx"
            src="../../static/index/start.png"
            alt=""
          />
          开始
        </view>
        <view
          v-if="isStart"
          @click="stop"
          class="bottom_button center"
          style="
            color: rgba(255, 255, 255, 1);
            background: rgba(110, 88, 170, 1);
            width: 160rpx;
          "
        >
          组间休息
        </view>
      </view>
    </view>
    <Countdown ref="countdownRef" />
    <!-- <view v-if="showCircle" class="countdown-circle">
		  <text class="countdown-number">{{ countdown }}</text>
		  <text class="tip-text">请保证设备处于竖直方向并静止3s</text>
		</view> -->
  </view>
</template>
<script>
import VersionHeader from "@/components/version-header/version-header.vue";
import VersionCanvas from "@/components/version-canvas/version-canvas.vue";
// import VersionSinglemodule from "@/components/profession-singlemodule/profession-singlemodule.vue";
import VueEvent from "../../VueEvent";
import Countdown from "@/components/countdown/countdown.vue";
import cal from "../../cal/vbt.js";
export default {
  data() {
    return {
      isStart: false,

      temp: [],
      counting: 0,
      history: [],
      stringtxt: "",
      filePath: "",
      pinlv: 400,

      isVersionControl: true, // 控制按钮样式的状态
      // isMuted: false, // 初始为非静音
      img_url: [
        "../../static/imgs/voice_open.png",
        "../../static/imgs/voice_close.png",
      ],
      measured_acceleration_y: [],
      measured_acceleration_x: [],
      measured_acceleration_z: [],
      angular_velocity_y: [],
      angular_velocity_x: [],
      angular_velocity_z: [],
      alpha: [],
      beta: [],
      gamma: [],
      maxDataLength: 10000, // 定义数组最大长度，可根据实际需求调整
      showCircle: false, // 控制倒计时圆圈是否显示
      countdown: 3, // 倒计时初始数字
      // simple和professional的button颜色
      accelarateData: [
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      ],
      n_base: 0,
      local_g: 0,
      intervalId1: null, // 用于存储定时器ID
      tips: "等待开始中...",

      sub_tips: false,
      version: false,
      intervalId: null, // 用于存储定时器ID
      options_train_target: ["增肌", "增强力量", "提升爆发力"],
      options_train_action: ["深蹲", "卧推", "硬拉"],
      options_target: {
        增肌: 1,
        增强力量: 2,
        提升爆发力: 3,
      },
      options_action: {
        深蹲: 1,
        卧推: 2,
        硬拉: 3,
      },
      aim: VueEvent.sharedData.aim,
      action: VueEvent.sharedData.action,
      v_loss: 30,

      group: 0,
      index: 0,
      rm: "",
      burden: "",

      //用于唯一确定负荷弹窗
      burden_Modal: false,
      check_burden: false,
      r: 0, // 计时器的秒数
      timer: null, // 用来存储定时器ID，方便停止
      arrs: [
        {
          name: "平均速度",
          value: 0,
          unit: "m/s",
        },
        {
          name: "峰值速度",
          value: 0,
          unit: "m/s",
        },
        {
          name: "平均功率",
          value: 0,
          unit: "w",
        },
        {
          name: "峰值功率",
          value: 0,
          unit: "w",
        },

        {
          name: "平均发力",
          value: 0,
          unit: "N",
        },
        {
          name: "发力峰值",
          value: 0,
          unit: "N",
        },
        {
          name: "发力率",
          value: 0,
          unit: "m/s",
        },
        {
          name: "功率损失",
          value: 0,
          unit: "%",
        },

        {
          name: "冲量",
          value: 0,
          unit: "kgm/s",
        },
        {
          name: "净冲量",
          value: 0,
          unit: "kgm/s",
        },
        {
          name: "做功量",
          value: 0,
          unit: "J",
        },
        {
          name: "本组做功",
          value: 0,
          unit: "J",
        },

        {
          name: "功率峰损",
          value: 0,
          unit: "%",
        },
        {
          name: "速度峰损",
          value: 0,
          unit: "%",
        },
        {
          name: "相对功率",
          value: 0,
          unit: "W/KG",
        },
        {
          name: "相对功率峰",
          value: 0,
          unit: "m/s",
        },

        {
          name: "离心速度",
          value: 0,
          unit: "m/s",
        },
        {
          name: "离心峰速",
          value: 0,
          unit: "m/s",
        },
        {
          name: "离心时间",
          value: 0,
          unit: "s",
        },
        {
          name: "RPD",
          value: 0,
          unit: "W/s",
        },

        {
          name: "0.2s速度",
          value: 0,
          unit: "m/s",
        },
        {
          name: "0.2s功率",
          value: 0,
          unit: "w",
        },
        {
          name: "0.2s发力",
          value: 0,
          unit: "N",
        },
        {
          name: "0.2s冲量",
          value: 0,
          unit: "kgm/s",
        },

        {
          name: "卡路里",
          value: 0,
          unit: "kcal",
        },
        {
          name: "总卡路里",
          value: 0,
          unit: "kcal",
        },
        {
          name: "OPL",
          value: 0,
          unit: "kg",
        },

        {
          name: "向心时间",
          value: 0,
          unit: "s",
        },
      ],
    };
  },
  components: {
    VersionHeader,
    VersionCanvas,
    Countdown,
  },
  computed: {
    // ?? 计算属性，保证 isMuted 自动更新
    isMuted() {
      return VueEvent.sharedData.isMuted;
    },
    red_none() {
      if (this.v_loss > 40) {
        let percentage = 100 - this.v_loss;
        console.log("red_none", percentage);
        return `${percentage}%`;
      }
      console.log("red_none 60%");
      return "60%";
    },
    red_cover() {
      if (this.v_loss > 40) {
        let percentage = this.v_loss;
        console.log("red_cover", percentage);
        return `${percentage}%`;
      }
      console.log("red_cover 0%");
      return "0%";
    },
    green_none() {
      if (this.v_loss < 20) {
        let percentage = this.v_loss;
        console.log("green_none", percentage);
        return `${percentage}%`;
      }
      console.log("green_none 20%");
      return "20%";
    },
    green_cover() {
      if (this.v_loss < 20) {
        let percentage = 20 - this.v_loss;
        console.log("green_cover", percentage);
        return `${percentage}%`;
      }
      console.log("green_cover 0%");
      return "0%";
    },
    circlePosition() {
      let percentage = this.v_loss;
      return `${percentage}%`;
    },
    circle() {
      if (this.v_loss <= 20) {
        return "2px solid rgba(165, 214, 63, 0.8)";
      } else if (this.v_loss <= 40) {
        return "2px solid rgba(110, 88, 170, 1)";
      } else {
        return "2px solid rgba(212, 48, 48, 0.6)";
      }
    },
  },
  onLoad() {
    this.filePath = `${uni.env.USER_DATA_PATH}/result.txt`;
    this.createFile();
    // this.isMuted = VueEvent.sharedData.isMuted;
  },
  onHide() {
    this.stopRequest();
    VueEvent.stopListeningAccelerometer();
  },
  onUnload() {
    // 页面被销毁时执行
    this.executeFunction();
    VueEvent.stopListeningAccelerometer();
    // this.isMuted = VueEvent.sharedData.isMuted;
  },
  // onBackPress(){
  // 	this.isMuted = VueEvent.sharedData.isMuted;
  // },
  methods: {
    // 创建文件
    createFile() {
      const fs = uni.getFileSystemManager();
      fs.writeFile({
        filePath: this.filePath,
        data: "", // 初始内容为空
        encoding: "utf8",
        success: (res) => {
          console.log("文件创建成功");
        },
        fail: (err) => {
          console.error("创建文件失败", err);
        },
      });
    },
    toggleMute() {
      VueEvent.changeVoice(); // ?? 切换静音状态
      console.log("现在是：", VueEvent.sharedData.isMuted);
      console.log("现在是：", this.isMuted);
    },
    onPickerChange_train_target(event) {
      const { value } = event.detail;
      this.aim = this.options_train_target[value];
      this.check_burden_value();
    },

    onPickerChange_train_action(event) {
      const { value } = event.detail;
      this.action = this.options_train_action[value];
      this.check_burden_value();
    },
    onFocus() {
      if (
        this.aim === "" ||
        this.action === "" ||
        this.rm === "" ||
        this.burden === ""
      ) {
        uni.showModal({
          title: "提示",
          content: "请先完善信息",
          showCancel: false,
          confirmText: "我已了解",
          success: (res) => {
            if (res.confirm) {
              console.log("用户点击了确定");
            }
          },
        });
        return true;
      }
      return false;
    },
    onInputFocus() {
      console.log(this.aim, this.action, this.rm);
      if (this.aim === "" || this.action === "" || this.rm === "") {
        if (!this.burden_Modal) {
          this.burden_Modal = true;
          uni.showModal({
            title: "提示",
            content: "请先完善训练目的，训练动作和1rm的信息",
            showCancel: false,
            confirmText: "我已了解",
            success: (res) => {
              if (res.confirm) {
                console.log("用户点击了确定");
              }
              // 当弹窗关闭后，重置标志位，以便下次还能触发
              this.burden_Modal = false;
            },
          });
        }
      }
      return false;
    },
    check_bd_value() {
      if (isNaN(this.burden)) {
        uni.showToast({
          title: "负荷只能为数字，请重新输入",
          icon: "none",
        });
        this.burden = "";
        return;
      }
    },
    check_burden_value() {
      if (isNaN(this.rm)) {
        uni.showToast({
          title: "1RM只能为数字，请重新输入",
          icon: "none",
        });
        this.rm = "";
        return;
      }
      if (this.aim !== "" && this.action !== "" && this.rm !== "") {
        if (!this.check_burden) {
          this.check_burden = true;
          uni.request({
            url: "http://182.92.108.71:5001/get_suggest",
            method: "POST", // 假设是POST请求，根据实际情况调整请求方式
            data: {
              aim: this.options_target[this.aim] - 1, // 训练目的
              action: this.options_action[this.action] - 1, // 训练动作
              lrm: this.rm,
            },
            header: {
              "Content-Type": "application/json", // 根据服务器要求设置 Content-Type
            },
            success: (res) => {
              if (res.statusCode === 200) {
                // this.accelarateData = res.data.msg;
                console.log("建议信息：", res.data);
                uni.showModal({
                  title: "提示",
                  content:
                    "建议负重" +
                    res.data.Suggest[0].toFixed(1) +
                    "kg-" +
                    res.data.Suggest[1].toFixed(1) +
                    "kg",
                  showCancel: false,
                  confirmText: "我已了解",
                  success: (res) => {
                    if (res.confirm) {
                      // console.log('用户点击了确定');
                      // 当弹窗关闭后，重置标志位，以便下次还能触发
                      this.check_burden = false;
                    }
                  },
                });
              } else {
                reject(`前置请求失败，状态码：${res.statusCode}`);
              }
            },
            fail: (err) => {
              reject(`前置请求错误：${err.errMsg}`);
            },
          });
        }
      }
    },
    stop() {
      if (this.isStart) {
        uni.showModal({
          // title: '1RM是什么?',
          content: "停止训练后将清除数据",
          showCancel: true,
          confirmText: "确定",
          success: (res) => {
            if (res.confirm) {
              // 用户点击了确定
              this.isStart = false;
              console.log("点击停止了！！！！！！");
              this.addlast();
              this.stopRequest();

              this.openFile();
              // this.savetxt();
              this.group = this.group + 1;
              this.index = 0;

              this.arrs[0].value = 0;
              this.arrs[1].value = 0;
              this.arrs[2].value = 0;
              this.arrs[3].value = 0;

              this.arrs[4].value = 0;
              this.arrs[5].value = 0;
              this.arrs[6].value = 0;
              this.arrs[7].value = 0;

              this.arrs[8].value = 0;
              this.arrs[9].value = 0;
              this.arrs[10].value = 0;
              this.arrs[11].value = 0;

              this.arrs[12].value = 0;
              this.arrs[13].value = 0;
              this.arrs[14].value = 0;
              this.arrs[15].value = 0;

              this.arrs[16].value = 0;
              this.arrs[17].value = 0;
              this.arrs[18].value = 0;
              this.arrs[19].value = 0;

              this.arrs[20].value = 0;
              this.arrs[21].value = 0;
              this.arrs[22].value = 0;
              this.arrs[23].value = 0;

              this.arrs[24].value = 0;
              this.arrs[25].value = 0;
              this.arrs[26].value = 0;
              this.arrs[27].value = 0;
            } else if (res.cancel) {
            }
          },
        });
      } else {
        uni.showToast({
          title: "请先点击开始~",
          icon: "none",
        });
        return;
      }
    },
    addlast() {
      const fs = uni.getFileSystemManager();
      const dataToAppend = JSON.stringify(this.temp);
      // this.history.push(this.temp);
      // 追加写入文件
      fs.appendFile({
        filePath: this.filePath,
        data: "更新了" + "\n" + dataToAppend + "\n", // 每次数据后换行
        encoding: "utf8",
        success: () => {
          console.log("写入文件成功！");
        },
        fail: (err) => {
          console.error("写入文件失败", err);
        },
      });
    },
    openFile() {
      console.log("正在打开文件");
      uni.openDocument({
        filePath: this.filePath,
        fileType: "txt",
        showMenu: true, // 允许出现分享功能
        success: (res) => {
          console.log("文件打开成功");
        },
        fail: (err) => {
          console.error("文件打开失败", err);
        },
      });
    },
    start() {
      // this.sendRequest();
      // return ;
      if (this.isStart) {
        uni.showToast({
          title: "正在进行中~",
          icon: "none",
        });
        return;
      } else {
        if (this.onFocus() === true) {
          return;
        }
        this.isStart = true;
        VueEvent.init_Accelerometer();
        VueEvent.startListeningAccelerometer();
        console.log("展示倒计时圈");
        // this.show_clock();
        this.$refs.countdownRef.startCountdown();
        this.startRequest();
      }
    },

    sendRequest() {
      this.measured_acceleration_x =
        VueEvent.sharedData.measured_acceleration_x;
      this.measured_acceleration_y =
        VueEvent.sharedData.measured_acceleration_y;
      this.measured_acceleration_z =
        VueEvent.sharedData.measured_acceleration_z;
      this.alpha = VueEvent.sharedData.alpha;
      this.beta = VueEvent.sharedData.beta;
      this.gamma = VueEvent.sharedData.gamma;
      let res = cal.complex_new(
        this.options_target[this.aim] - 1,
        this.options_action[this.action] - 1,
        this.rm,
        this.burden,
        this.index,
        this.local_g
      );
      console.log("获取到的结果是\n", res);
      if (res.msg.length > 0) {
        const lastMsg = res.msg[res.msg.length - 1];
        if (lastMsg["updata_flag"] === 1) {
          console.log("开始更新");
          const fs = uni.getFileSystemManager();
          this.local_g = lastMsg["local_g"];
          this.temp = res.v;

          const dataToAppend = JSON.stringify(this.temp);
          const x = JSON.stringify(this.measured_acceleration_x);
          const y = JSON.stringify(this.measured_acceleration_y);
          const z = JSON.stringify(this.measured_acceleration_z);
          const alpha = JSON.stringify(this.alpha);
          const beta = JSON.stringify(this.beta);
          const gamma = JSON.stringify(this.gamma);
          // 追加写入文件
          fs.appendFile({
            filePath: this.filePath,
            data:
              "更新了" +
              "\n" +
              "measured_acceleration_x\n" +
              x +
              "\n" +
              "measured_acceleration_y\n" +
              y +
              "\n" +
              "measured_acceleration_z\n" +
              z +
              "\n" +
              "alpha\n" +
              alpha +
              "\n" +
              "beta\n" +
              beta +
              "\n" +
              "gamma\n" +
              gamma +
              "\n" +
              "acceleration_data\n" +
              dataToAppend +
              "\n",
            encoding: "utf8",
            success: () => {
              console.log("写入文件成功！");
              // completedRequests++;
              // if (completedRequests === requests.length) {
              //   this.openFile();  // 所有请求完成后打开文件
              // }
            },
            fail: (err) => {
              console.error("写入文件失败", err);
            },
          });
          VueEvent.del_Accelerometer(lastMsg["delete_index"]);
          console.log("清除的数据index是", lastMsg["delete_index"]);
          this.index = lastMsg["n_base"];
          this.local_g = lastMsg["local_g"];
          if (lastMsg["avg_speed"].toFixed(2) != 0.0 && this.isStart == true) {
            console.log("数据发生变化");
            // this.group = lastMsg["第几组"];
            // this.index = lastMsg["n_base"];
            this.v_loss = (lastMsg["loss"] * 100).toFixed(1); // 保留两位小数
            this.arrs[0].value = lastMsg["avg_speed"].toFixed(2); // 平均速度
            this.arrs[1].value = lastMsg["max_speed"].toFixed(2); // 峰值速度
            this.arrs[2].value = lastMsg["avg_power"].toFixed(2); // 平均功率
            this.arrs[3].value = lastMsg["max_power"].toFixed(2); // 峰值功率

            this.arrs[4].value = lastMsg["averagy_force_value"].toFixed(2); // 平均发力
            this.arrs[5].value = lastMsg["max_strive"].toFixed(2); // 发力峰值
            this.arrs[6].value = lastMsg["strive_rate"].toFixed(2); // 发力率
            this.arrs[7].value = lastMsg["power_loss"].toFixed(2); // 功率损失

            this.arrs[8].value = lastMsg["impulse"].toFixed(2); // 冲量
            this.arrs[9].value = lastMsg["net_impulse"].toFixed(2); // 净冲量
            this.arrs[10].value = lastMsg["work"].toFixed(2); // 做功量
            this.arrs[11].value = lastMsg["pre_work"].toFixed(2); // 本组做功

            this.arrs[12].value = lastMsg["power_max_loss"].toFixed(2); // 功率峰损
            this.arrs[13].value = lastMsg["speed_max_loss"].toFixed(2); // 速度峰损
            this.arrs[14].value = lastMsg["relative_power"].toFixed(2); // 相对功率
            this.arrs[15].value = lastMsg["relative_max_power"].toFixed(2); // 相对功率峰

            this.arrs[16].value = lastMsg["centrifugal_speed"].toFixed(2); // 离心速度
            this.arrs[17].value = lastMsg["centrifugal_max_speed"].toFixed(2); // 离心峰速
            this.arrs[18].value = lastMsg["centrifugal_time"].toFixed(2); // 离心时间
            this.arrs[19].value = lastMsg["rpd"].toFixed(2); // RPD

            this.arrs[20].value = lastMsg["zero_point_two_speed"].toFixed(2); // 0.2s速度
            this.arrs[21].value = lastMsg["zero_point_two_power"].toFixed(2); // 0.2s功率
            this.arrs[22].value = lastMsg["zero_point_two_strive"].toFixed(2); // 0.2s发力
            this.arrs[23].value = lastMsg["zero_point_two_momentum"].toFixed(2); // 0.2s冲量

            this.arrs[24].value = lastMsg["calorie"].toFixed(2); // 卡路里
            this.arrs[25].value = lastMsg["total_calorie"].toFixed(2); // 总卡路里
            this.arrs[26].value = lastMsg["opl"].toFixed(2); // opl
            this.arrs[27].value = lastMsg["toward_heart_time"].toFixed(2); // 向心时间
            // console.log("每次获取的值", this.arrs);
            this.tips = lastMsg["message"];
            if (
              lastMsg["message"] === "建议调整重量，减重" ||
              lastMsg["message"] === "建议调整重量,减重"
            ) {
              lastMsg["message"] = "建议减少重量";
              this.tips = "建议减少重量";
            } else if (
              lastMsg["message"] === "建议调整重量，增重" ||
              lastMsg["message"] === "建议调整重量,增重"
            ) {
              lastMsg["message"] = "建议增加重量";
              this.tips = "建议增加重量";
            }
            console.log("当前计数", this.test_flag);
            this.test_flag = this.test_flag + 1;
            if (lastMsg["message"] === "请继续训练") {
              this.textToVoice(
                lastMsg["averagy_v_value"].toFixed(2) + "米每秒"
              );
            } else {
              this.textToVoice(lastMsg["message"]);
            }
          } else {
            console.log("数据没有变化");
          }
        } else {
          console.log("update_flag为0");
        }
      }
    },

    //设置定时器每隔一段时间发送一次请求
    startRequest() {
      console.log("start to post message");
      this.index = 0;
      if (this.intervalId) {
        return; // 如果定时器已经存在，防止重复点击
      }

      // 使用 setInterval 设置定时器
      console.log("当前频率", this.pinlv);
      this.intervalId = setInterval(() => {
        this.sendRequest();
        console.log("我发送了一次请求");
      }, this.pinlv); // 每隔400毫秒发送一次请求
    },
    // 清除发送请求的定时器
    stopRequest() {
      console.log("stop to post message");
      // VueEvent.init_Accelerometer();
      VueEvent.stopListeningAccelerometer();
      if (this.intervalId) {
        clearInterval(this.intervalId); // 清除定时器
        this.intervalId = null; // 重置定时器ID
      }
    },
    tips_1rm() {
      uni.showModal({
        title: "1RM是什么?",
        content:
          "1RM：以正确的技术所能举起一次最大重量\n\n填写后会自动为您计算本次训练的最佳负荷",
        showCancel: false,
        confirmText: "我已了解",
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击了确定");
          }
        },
      });
    },
    gotoDefine() {
      uni.navigateTo({
        url: "/pages/define/define",
      });
    },
    goOneRm() {
      uni.switchTab({
        url: "/pages/jobOneRm/jobOneRm",
      });
    },
    textToVoice(text) {
      if (this.isMuted == true) return;

      var pluginSI = requirePlugin("WechatSI");
      var innerAudioSI = wx.createInnerAudioContext();

      pluginSI.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: text,
        // speed: 9, // ?? 语速加快 40%（默认值 5，可调整 6-9）
        success: function (res) {
          console.log("succ tts", res.filename);
          innerAudioSI.src = res.filename;
          innerAudioSI.playbackRate = 1.5;
          innerAudioSI.play();

          // 语音播放结束时，清理音频对象
          innerAudioSI.onEnded(() => {
            console.log("语音播放完毕");
            innerAudioSI.stop();
            innerAudioSI.destroy();
          });
        },
        fail: function (res) {
          console.log("fail tts", res);
        },
      });
      return innerAudioSI;
    },

    stop_group() {
      if (!this.isStart) {
        uni.showToast({
          title: "请先点击开始~",
          icon: "none",
        });
        return;
      }
      uni.showModal({
        // title: '1RM是什么?',
        content: "确定结束本组训练吗",
        showCancel: true,
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            // 增加组的计数
            this.stopRequest();
            if (this.index !== 0) {
              this.group = this.group + 1;
            }
            this.index = 0;
            // 初始化 r 为 1，每次点击重新开始计时
            this.r = 1;

            // 更新显示提示信息
            this.updateTips();

            // 启动计时器，每隔一秒更新一次 r
            if (this.timer) {
              clearInterval(this.timer); // 清除上一个定时器（防止重复计时）
            }
            this.startTimer();
          }
        },
      });
    },
    // 在methods中定义播放音频的函数
    playAudio(src) {
      const audioContext = uni.createInnerAudioContext(); // 创建音频上下文对象
      audioContext.src = src; // 设置音频源，替换为你的音频文件路径
      audioContext.autoplay = true; // 设置自动播放

      // 监听播放事件
      audioContext.onPlay(() => {
        console.log("音频开始播放");
      });

      // 监听播放错误事件
      audioContext.onError((res) => {
        console.log("音频播放出错：", res.errMsg);
      });

      // 监听播放完成事件
      audioContext.onEnded(() => {
        console.log("音频播放完毕");
      });

      // 播放音频
      audioContext.play();
    },
    show_clock() {
      if (this.timer) {
        clearInterval(this.timer); // 清除上一个定时器（防止重复计时）
        this.countdown = 3; // 重置倒计时数字
      }

      this.tips = "等待开始中...";
      this.showCircle = true;
      var lst = VueEvent.sharedData.clock;
      console.log("音频地址是：", lst);
      var idx = 0;

      // 启动倒计时定时器
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          // 每次倒计时数字更新前，立即播放对应的音频
          if (!this.isMuted) {
            this.playAudio(lst[idx]);
          }

          this.countdown--; // 更新倒计时数字
          idx++; // 更新音频索引
        } else {
          // 倒计时结束，播放"开始"语音
          if (!this.isMuted) {
            this.playAudio(lst[idx]);
          }

          clearInterval(timer); // 清除定时器
          this.countdown = 3; // 重置倒计时数字
          this.showCircle = false;
          // this.startRequest(); // 倒计时结束后，开始请求
        }
      }, 1000); // 每秒检查一次
    },
  },
};
</script>
<style scoped lang="scss">
.slider-bar {
  position: relative;
  width: 460rpx;
  height: 20rpx;
  display: flex;
  align-items: center;
  margin: 10px 0;
  border-radius: 16rpx;
}

.bar {
  height: 100%;
}

.red_none {
  background: rgba(255, 255, 255, 0.8);

  border: 1px solid rgba(212, 48, 48, 0.6);
  border-radius: 8px 0px 0px 8px;
}

.red_cover {
  background: rgba(212, 48, 48, 0.6);
  // border: 1px solid rgba(212, 48, 48, 0.6);
}

.purple {
  background: rgba(110, 88, 170, 1);

  border: 1px solid rgba(110, 88, 170, 1);
}

.green_none {
  border-radius: 0px 8px 8px 0px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(165, 214, 63, 0.8);
}

.green_cover {
  background: rgba(165, 214, 63, 0.8);
}

.circle {
  position: absolute;
  top: -2px;
  width: 14px;
  height: 14px;
  background-color: white;
  border-radius: 50%;
  border: 2px solid purple;
  transition: left 0.3s;
}

.tip-text {
  color: white;
  text-align: center;
  font-size: 30rpx;
  margin: 20rpx;
}

.tips_header {
  // width: 360px;
  width: 652rpx;
  height: 38rpx;
  border-radius: 8rpx;
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0px 1px 2px rgba(124, 124, 126, 0.15);
  /** 文本1 */
  font-size: 24rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 31rpx;
  color: rgba(110, 88, 170, 1);
}

.gi_module {
  width: 132rpx;
  height: 60rpx;
  opacity: 1;
  border-radius: 8rpx;
  background: rgba(110, 88, 170, 0.1);
  box-shadow: 1px 1px 2px rgba(124, 124, 126, 0.15);
  /** 文本1 */
  font-size: 28rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 63rpx;
  color: rgba(110, 88, 170, 1);
}

.s_n {
  /** 文本2 */
  font-size: 48rpx;
  font-weight: 400;
  width: 50rpx;
}

.labels {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  font-size: 20rpx;
  color: gray;
}

.layout {
  height: 100%;
  background: rgba(110, 88, 170, 0.02);
  font-family: "优设标题黑";
}

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.countdown-circle {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 100px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.countdown-number {
  font-size: 130rpx;
  color: white;
  margin-bottom: 10px;
}

.tip-text {
  color: white;
  text-align: center;
  font-size: 30rpx;
  margin: 20rpx;
}

.loss_name {
  font-size: 36rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 47rpx;
  color: rgba(0, 0, 0, 1);
  margin-right: 20rpx;
}

.group_index {
  letter-spacing: 10rpx;
  font-size: 48rpx;
  font-weight: 400;
  line-height: 80rpx;
  background: rgba(110, 88, 170, 1);
  color: rgba(255, 255, 255, 1);
}
.index_box {
  margin: 20rpx 0rpx;
  flex-wrap: wrap;
  /* 允许换行 */
  justify-content: space-between;
}

.index_module {
  margin: 5rpx 10rpx;
  width: 160rpx;
  height: 84rpx;
  // width: 272rpx;
  // height: 168rpx;
  mix-blend-mode: multiply;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0px 2px 4px rgba(110, 88, 170, 0.23);
  color: rgba(110, 88, 170, 1);
}

.index_name {
  // margin-top: 12rpx;
  /** 文本1 */
  font-size: 24rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 31rpx;
  color: rgba(124, 124, 126, 1);
}

.index_value {
  width: 100rpx;
  font-size: 20rpx;
}

.index_unit {
  font-size: 24rpx;
}

.choose_train {
  // margin: 22rpx 48rpx;
  width: 272rpx;
  // border: 1px solid black;
  height: 128rpx;
  mix-blend-mode: multiply;
  opacity: 1;
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0px 2px 4px rgba(110, 88, 170, 0.23);
}

.train_title {
  height: 52rpx;
  font-size: 32rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 42rpx;
  color: rgba(255, 255, 255, 1);
  background: rgba(110, 88, 170, 1);
}

.click_choose {
  height: 75rpx;
  font-size: 36rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 29rpx;
  color: rgba(191, 191, 191, 1);
}

.br {
  width: 656rpx;
  height: 66rpx;
  mix-blend-mode: multiply;
  opacity: 1;
  border-radius: 16rpx;
  background: rgba(124, 124, 126, 0.05);
  margin: 28rpx auto;
}

.br_name {
  /** 文本1 */
  margin-left: 38rpx;
  margin-right: 390rpx;
  font-size: 32rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 42rpx;
  color: rgba(124, 124, 126, 1);
}

.br_value {
  font-size: 26rpx;
  color: rgba(191, 191, 191, 1);
  width: 150rpx;
}

.bottom_button {
  height: 56rpx;
  opacity: 1;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 1);
  /** 文本1 */
  font-size: 32rpx;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 42rpx;
  color: rgba(110, 88, 170, 1);
  // border: 1px solid black;
}

.burden_tips {
  font-size: 16rpx;
  font-weight: 400;
  line-height: 21rpx;
  color: rgba(252, 0, 0, 1);
}

.end_group {
  /** 文本1 */
  height: 70rpx;
  font-size: 40rpx;
  font-weight: 400;
  line-height: 20.8px;
  color: rgba(110, 88, 170, 1);
  text-align: center;
  box-shadow: 0px 2px 4px rgba(110, 88, 170, 0.23);
}

.isStart {
  background: rgba(110, 88, 170, 1);
}

.not_Start {
  background: rgba(110, 88, 170, 0.02);
}

.stop_start {
  width: 100rpx;
}
</style>
